package com.shuorikeji.huohuo.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.shuorikeji.huohuo.R;

import java.lang.reflect.Field;


/**
 * Toast单例
 * <p>
 * Created by fangxiaotian on 2016/11/3.
 */

@SuppressLint("SoonBlockedPrivateApi")
public class ToastShowUtil {
    private static Field sFieldTN;
    private static Field sFieldTNHandler;

    public static void init() {
        try {
            sFieldTN = Toast.class.getDeclaredField("mTN");
            sFieldTN.setAccessible(true);
            sFieldTNHandler = sFieldTN.getType().getDeclaredField("mHandler");
            sFieldTNHandler.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Toast内容显示在屏幕中央
     *
     * @param context 上下文
     * @param string  toast的内容
     */
    public static void showToastCenter(Context context, String string) {
        try {
            Toast toastCenter = Toast.makeText(context, string, Toast.LENGTH_SHORT);
            View view = LayoutInflater.from(context).inflate(R.layout.toast_show_layout, null);
            TextView tvToastTips = view.findViewById(R.id.tv_toast_tips);
            tvToastTips.setText(string);//解决提示信息携带应用程序名称的现象
            //setGravity决定Toast显示位置
            toastCenter.setGravity(Gravity.CENTER, 0, 0);
            toastCenter.setView(view);
            hook(toastCenter);
            //调用show使得toast得以显示
            toastCenter.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * toast.show()之前调用该方法，能防止程序出现has already been added to the window manager的异常崩溃
     *
     * @param toast toast
     */
    private static void hook(Toast toast) {
        try {
            Object tn = sFieldTN.get(toast);
            Handler preHandler = (Handler) sFieldTNHandler.get(tn);
            sFieldTNHandler.set(tn, new SafelyHandlerWrapper(preHandler));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class SafelyHandlerWrapper extends Handler {
        private Handler impl;

        SafelyHandlerWrapper(Handler impl) {
            this.impl = impl;
        }

        @Override
        public void dispatchMessage(Message msg) {
            try {
                super.dispatchMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void handleMessage(Message msg) {
            impl.handleMessage(msg);
        }
    }
}
